from fastapi import Request
from tortoise.transactions import in_transaction
import os

from service import UserService, SongService
from common.result.Result import Result
from common.enum import BaseEnum
from util.log import Log
from util.array import Array
from util.str import Str
from util.token import Token

async def AuthSecretKey(req: Request, id: int):
    try:
        if Str.isBlank(id):
            return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)

        token = req.headers.get("token")
        payload = Token().verify_token(token)
        if payload == None:
            return Result.error(BaseEnum.TOKEN_INVALID_ERROR)
        
        user = await UserService.getUserByToken(token)
        if user == None:
            return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)
        
        # 验证用户是否可以听这首歌
        flag = True

        if flag == False:
            return Result.success({
                'abcxy': str(Array.randomNumberList(32, 0, 9))
            })
        
        secretKey = await SongService.getSecretKey(user.id, id)

        return Result.success(secretKey)
    except Exception as e:
        Log.error('获取 song 的播放 URL 异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)


